#include "socketqueue.h"

SocketQueue_NormalMsg::SocketQueue_NormalMsg(const QByteArray &array)
    : mArray(array) {}

void SocketQueue_NormalMsg::addData(const QByteArray &array) { mArray += array; }
QByteArray SocketQueue_NormalMsg::data() { return mArray; }
bool SocketQueue_NormalMsg::isVaild() { return true; }
bool SocketQueue_NormalMsg::isFinished() { return true; }


SocketQueue_FileMsg::SocketQueue_FileMsg(const QString &filePath, const QString &remotePath, const QString *serverDir)
    : mChecksum(QCryptographicHash::Md5), mRemotePath(remotePath), mServerDir(serverDir), mFile(filePath), mSize(mFile.size())
{
    mFile.open(QIODevice::ReadOnly);
}
SocketQueue_FileMsg::~SocketQueue_FileMsg() {
    if(mFile.isOpen())
        mFile.close();
}

QByteArray SocketQueue_FileMsg::data() {
    if(mRead == mSize) {
        emit sendFileFinished();

        QByteArray xml;
        QXmlStreamWriter xmlWriter(&xml);
        xmlWriter.writeStartDocument();
        xmlWriter.writeStartElement("SendFileFinished");
        xmlWriter.writeAttribute("Path", mRemotePath);
        bool equal = mServerDir != nullptr && QFileInfo(*mServerDir).filePath() == QFileInfo(mRemotePath).path();
        xmlWriter.writeAttribute("Update", QString::number(equal));
        xmlWriter.writeAttribute("Checksum", mChecksum.result().toHex());
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();
        mFinished = true;
        return xml;
    }
    QByteArray xml;
    QXmlStreamWriter xmlWriter(&xml);
    xmlWriter.writeStartDocument();
    xmlWriter.writeStartElement("SendFile");
    xmlWriter.writeAttribute("Path", mRemotePath);
    xmlWriter.writeAttribute("Ind", "0");
    xmlWriter.writeEndElement();
    xmlWriter.writeEndDocument();

    qint64 payloadSize = mPayloadSize - xml.length() - 9;
    qint64 bytesToRead = qMin(mSize - mRead, payloadSize);
    QByteArray data = mFile.read(bytesToRead);
    mChecksum.addData(data);
    mRead += bytesToRead;
    emit progress(mRead);
    return "$" + QByteArray((char*)&bytesToRead, 8) + data + xml;
}
bool SocketQueue_FileMsg::isVaild() {
    return mFile.isOpen();
}
bool SocketQueue_FileMsg::isFinished() {
    return mFinished;
}

